<?php

namespace Jinxing\Admin\Repositories;

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Littlebug\Repository\Repository;
use Jinxing\Admin\Models\Permission;

class PermissionRepository extends Repository
{
    public function __construct(Permission $model)
    {
        parent::__construct($model);
    }

    /**
     * @param $data
     *
     * @return array
     * @throws \Throwable
     */
    public function createPermission($data)
    {
        return DB::transaction(function () use ($data) {
            $permission = $this->create($data);

            // 添加超级管理员角色
            PermissionRoleRepository::instance()->create([
                'permission_id' => Arr::get($permission, 'id'),
                'role_id'       => config('admin.super_role_id'),
            ]);

            return $permission;
        });
    }

    /**
     * 删除权限
     *
     * @param $condition
     *
     * @return int
     * @throws \Throwable
     */
    public function deletePermission($condition)
    {
        return DB::transaction(function () use ($condition) {
            $this->delete($condition);

            return PermissionRoleRepository::instance()->delete(['permission_id' => Arr::get($condition, 'id')]);
        });
    }
}
